<?php
require 'Slim/Slim.php';
require_once 'DBRequestHandler.php';
require_once 'PasswordHash.php';


\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$userName = NULL;
 
/**
 * Verifying required params posted or not
 */
function verifyRequiredParams($required_fields) {
    $error = false;
    $error_fields = "";
    $request_params = array();
    $request_params = $_REQUEST;
    // Handling PUT request params
    if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
        $app = \Slim\Slim::getInstance();
        parse_str($app->request()->getBody(), $request_params);
    }
    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .=  $field . ', ';
        }
    }
 
    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        //user of -2 in substr concatenation removes trailing comma
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["error"] = true;
        $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is/are missing or empty';
        echoRespnse(400, $response);
        $app->stop();
    }
}
 
/**
 * Validating email address
 * Note: checks for form only, not existence
 */
function validateEmail($email) {
    $app = \Slim\Slim::getInstance();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response["error"] = true;
        $response["message"] = 'Email address is not valid';
        echoRespnse(400, $response);
        $app->stop();
    }
}
 
/**
 * Echoing json response to client
 * @param String $status_code Http response code
 * @param Int $response Json response
 */
function echoRespnse($status_code, $response) {
    $app = \Slim\Slim::getInstance();
    // Http response code
    $app->status($status_code);
 
    // setting response content type to json
    $app->contentType('application/json');
 
    echo json_encode($response);
}


/**
 * User Registration
 * url - /register
 * method - POST
 * params - name, email, password
 */
$app->post('/register', function() use ($app) {
                
            // check for required parameters
            verifyRequiredParams(array('user', 'pass', 'fname', 'lname', 'email'));     
            
            $response = array();
 
            // reading post params
            $user = $app->request->post('user');
            $pass = $app->request->post('pass');
            $fname = $app->request->post('fname');
            $lname = $app->request->post('lname');
            $email = $app->request->post('email');
 
            // validating email address
            validateEmail($email);
 
            $db = new DBRequestHandler;
            $res = $db->newUser($user, $pass, $fname, $lname, $email);
 
            if ($res == 0) {
                $response["error"] = false;
                $response["message"] = "You are successfully registered";
                echoRespnse(201, $response);
            } else if ($res == 1) {
                $response["error"] = true;
                $response["message"] = "Username or Password too short";
                echoRespnse(201, $response);
            } else if ($res == 2) {
                $response["error"] = true;
                $response["message"] = "This username is in use.  Please try a different one";
                echoRespnse(200, $response);
            }
        });
        
/**
 * User Login
 * url - /login
 * method - POST
 * params - email, password
 */
$app->post('/login', function() use ($app) {
            // check for required parameters
            verifyRequiredParams(array('user', 'pass'));
 
            // reading post params
            $user = $app->request()->post('user');
            $password = $app->request()->post('pass');
            $response = array();
 
            $db = new DBRequestHandler;
            $res = $db->authenticate($user, $password);
            // check for correct email and password
            if ($res[0] == 0) {

                $response['error'] = false;
                $response['API'] = $res[1];
                $response['user'] = $res[2];
                $response['message'] = 'Login Successful';
                echoRespnse(200, $response);
                
                
            } else {
                // invalid user/pass
                $response['error'] = true;
                $response['API'] = 0;
                $response['message'] = 'Invalid username or password.  Please try again';
                echoRespnse(201, $response);
            }
 
            
        });
        
/**
 * User Registration
 * url - /register
 * method - POST
 * params - name, email, password
 */
$app->post('/newItem', function() use ($app) {
                
            // check for required parameters -- taken care of at application level
            //verifyRequiredParams(array('id', 'name', 'serial'));     
                          
            $response = array();
 
            // reading post params
            $id = $app->request->post('id');
            $name = $app->request->post('name');
            $serial = $app->request->post('serial');
            $acc = $app->request->post('accessories');
            $sf = $app->request->post('specialFeatures');
            $os = $app->request->post('operatingSystem');
            $pgs = $app->request->post('pages');
            $othi = $app->request->post('otherInfo'); 

 
            $db = new DBRequestHandler;
            $res = $db->addNewItem($id, $name, $serial, $acc, $sf, $os, $pgs, $othi);
 
            if ($res == 0) {
                $response["error"] = false;
                $response["message"] = "Item Added";
                echoRespnse(200, $response);
            } else if ($res == 1) {
                $response["error"] = true;
                $response["message"] = "Error adding item";
                echoRespnse(201, $response);
            } else if ($res == 2) {
                $response["error"] = true;
                $response["message"] = "Duplicate ItemID.  Cannot add";
                echoRespnse(201, $response);
            }
            else if ($res == 3) {
                $response["error"] = true;
                $response["message"] = "Duplicate Serial Number.  Cannot add";
                echoRespnse(201, $response);
            }
        });      
        
/**
 * Item edits
 * url - /register
 * method - POST
 * params - id, name, serial, accessories, specialFeatures, operatingSystem, pages, otherInfo.
 */
$app->post('/editItem', function() use ($app) {
                
                
            // check for required parameters
            //verifyRequiredParams(array('Name', 'Serial', 'Accessory', 'SpecialFeature', 'OperatingSystem', 'Pages', 'OtherInfo'));     
            
            $response = array();
 
            // reading post params            
            $itemID = $app->request->post("id");            
            $name = $app->request->post('name');
            $serial = $app->request->post('serial');
            $acc = $app->request->post('accessories');
            $sf = $app->request->post('specialFeatures');
            $os = $app->request->post('operatingSystem');
            $pgs = $app->request->post('pages');
            $othi = $app->request->post('otherInfo'); 
            
   
            
            //attempt database edit
            $db = new DBRequestHandler;
            $res = $db->editItemAttributes($itemID, $name, $serial, $acc, $sf, $os, $pgs, $othi);
 
            $response = array();
            $successUpdate = 0;
            
            //confirm that all attributes were successfully added
            
            for ($i = 0; $i < 7; $i++){
                //echo $res[$i];    
                if($res[$i] != 0){
                    $successUpdate = 1;
                }
            }
            
 
            if ($successUpdate == 0) {
                $response["error"] = false;
                $response["message"] = "Changes Saved";
                echoRespnse(200, $response);
            } else if ($successUpdate == 1) {
                $response["error"] = true;
                $response["message"] = "Error saving changes";
                echoRespnse(201, $response);
            }            
        });
        
        
/**
 * Get inventory
 * url - /Inventory list
 * method - GET
 * params - none
 */
$app->get('/InventoryList', function() use ($app) {
                
            // check for required parameters
            //verifyRequiredParams(array('Acessory', 'SpecialFeature', 'OperatingSyatem', 'Pages', 'OtherInfo'));     
            
            $res = array();
            $response = array();        
            
            //query db
            $db = new DBRequestHandler;
            $res = $db->getItemList();
            $resLength = sizeof($res);
            
            //add item print strings and item IDs to result list
            $counter = 0;            
            for ($i = 0; $i <= $resLength - 2; $i += 2){                   
                $response["display" . $counter] = $res[$i];
                $response["id" . $counter] = $res[($i + 1)];
                $counter++;   
            }
            
            //add length attribute to result list
            $response["Length"] = ($resLength / 2);
            
            echoRespnse(200, $response);
            
            /*} else if ($successUpdate == 1) {
                $response["error"] = true;
                $response["message"] = "Error adding item";
                echoRespnse(201, $response);
            }*/            
        });    
    

 /* Single item retrieval
 * url - /getItem
 * method - GET
 * params - ID
 */
$app->get('/getItem', function() use ($app) {
                
            // check for required parameters
            //verifyRequiredParams(array('Acessory', 'SpecialFeature', 'OperatingSyatem', 'Pages', 'OtherInfo'));     
            
            
            $id = $app->request->get('id');
            
            
            $res = array();
            $response = array();        
            
            //attempt database add
            $db = new DBRequestHandler;
            $res = $db->getItemDetail($id);
            
            
            if ($res[0] == 0) {

                $response['error'] = false;
                $response['ItemID'] = $res[1];
                $response['Name'] = $res[2];
                $response['Serial'] = $res[3];
                $response['Accessories'] = $res[4];
                $response['Special Features'] = $res[5];
                $response['Operating System'] = $res[6];
                $response['Pages'] = $res[7];
                $response['Other Information'] = $res[8];
                $response['Checked in or out'] = $res[9];
                $response['message'] = 'retrieval succesful';
                echoRespnse(200, $response);
                
                
            } else {
                // invalid item
                $response['error'] = true;
                $response['message'] = 'retrieval failed';
                echoRespnse(201, $response);
            }

});




        
        
/**
 * Checkin
 * url - /checkinItem
 * method - POST
 * params - id (itemID)
 */
$app->post('/checkinItem', function() use ($app) {
            
            // reading post params
            $id = $app->request()->post('id');
            $response = array();
 
            $db = new DBRequestHandler;
            $res = $db->checkinItem($id);
            // check for correct email and password
            if ($res == 0) {
                
                $response['error'] = false;                
                $response['message'] = 'Item: '. $id . ' checked in';
                echoRespnse(200, $response);               
                
            } else {
                // invalid user/pass
                $response['error'] = true;                
                $response['message'] = 'Could not check out item: ' .$id;
                echoRespnse(201, $response);
            }
            
        });
        
        
/**
 * item checkout
 * url - /checkoutItem
 * method - POST
 * params - user, itemID
 */
$app->post('/checkoutItem', function() use ($app) {
            
            // reading post params
            $user = $app->request()->post('user');
            $id = $app->request()->post('id');
            $response = array();
 
            $db = new DBRequestHandler;
            $res = $db->checkoutItem($id, $user);
            // check for correct email and password
            if ($res == 0) {
                
                $response['error'] = false;                
                $response['message'] = 'Item: '. $id . ' checked out by user: ' . $user;
                echoRespnse(200, $response);               
                
            } else {
                // invalid user/pass
                $response['error'] = true;                
                $response['message'] = 'Could not check out item: ' .$id. 'due to database error.  Please try again';
                echoRespnse(201, $response);
            }
            
        });
        
        
        
 /**
 * Get checkout history
 * url - /History
 * method - GET
 * params - none
 */
$app->get('/History', function() use ($app) {
                
            // check for required parameters
            //verifyRequiredParams(array('Acessory', 'SpecialFeature', 'OperatingSyatem', 'Pages', 'OtherInfo'));     
            
            //get post param:
            $id = $app->request()->get('id');
            
            $res = array();
            $response = array();        
            
            //query db
            $db = new DBRequestHandler;
            $res = $db->getHistory($id);
            $resLength = sizeof($res);
            
            
            //add item history strings to list
            $counter = 0;
            for ($i = 0; $i <= $resLength - 1; $i++){
                $response["display" . $counter] = $res[$i];
                $counter++;
            }
            $response["length"] = $resLength;    
            
            echoRespnse(200, $response);
            
            /*} else if ($successUpdate == 1) {
                $response["error"] = true;
                $response["message"] = "Error adding item";
                echoRespnse(201, $response);
            }*/            
        });
        
       
/**
 * Basic Search
 * url - /Inventory list
 * method - GET
 * params - none
 */
$app->get('/BasicSearch', function() use ($app) {
                
            // check for required parameters
            //verifyRequiredParams(array('Acessory', 'SpecialFeature', 'OperatingSyatem', 'Pages', 'OtherInfo'));     
            
            $res = array();
            $response = array();        
            
            $query = $app->request()->get('query');
            
            //query db
            $db = new DBRequestHandler;
            $res = $db->basicSearch($query);
            $resLength = sizeof($res);
            
            if($resLength == 0){
                $response["error"] = true;
                $response["message"] = "searched returned no results";
                echoRespnse(201, $response);
            }
            else{
            $response["error"] = false;
            //add item print strings and item IDs to result list
            $counter = 0;            
            for ($i = 0; $i <= $resLength - 2; $i += 2){                   
                $response["display" . $counter] = $res[$i];
                $response["id" . $counter] = $res[($i + 1)];
                $counter++;   
            }
            
            //add length attribute to result list
            $response["Length"] = ($resLength / 2);
            
            echoRespnse(200, $response);
            }        
        });    



/**
 * Advanced Search
 * url - /Inventory list
 * method - GET
 * params - none
 */
$app->get('/AdvSearch', function() use ($app) {
                
            // check for required parameters
            //verifyRequiredParams(array('Acessory', 'SpecialFeature', 'OperatingSyatem', 'Pages', 'OtherInfo'));     
            
            $res = array();
            $response = array();        
            
            $name = $app->request()->get('Name');
            $id = $app->request()->get('ItemID');
            $serial = $app->request()->get('SerialNum');
            $accessory = $app->request()->get('Accessory');
            $specialfeature = $app->request()->get('SpecialFeature');
            $os = $app->request()->get('OperatingSystem');
            
            //query db
            $db = new DBRequestHandler;
            $res = $db->advSearch($name, $id, $serial, $accessory, $specialfeature, $os);
            $resLength = sizeof($res);
            
            if($resLength == 0){
                $response["error"] = true;
                $response["message"] = "searched returned no results";
                echoRespnse(201, $response);
            }
            else{
            $response["error"] = false;
            //add item print strings and item IDs to result list
            $counter = 0;            
            for ($i = 0; $i <= $resLength - 2; $i += 2){                   
                $response["display" . $counter] = $res[$i];
                $response["id" . $counter] = $res[($i + 1)];
                $counter++;   
            }
            
            //add length attribute to result list
            $response["Length"] = ($resLength / 2);
            
            echoRespnse(200, $response);
            }        
        });                   

    /**
 * item deletion
 * url - /deleteItem
 * method - POST
 * params - user, itemID
 */
$app->post('/DeleteItem', function() use ($app) {
            
            // reading post params
            $id = $app->request()->post('id');
            $response = array();
 
            $db = new DBRequestHandler;
            $res = $db->deleteItem($id);
            // check for correct email and password
            if ($res == 0) {
                
                $response['error'] = false;                
                $response['message'] = 'Item: '. $id . ' deleted';
                echoRespnse(200, $response);               
                
            } else {
                // error
                $response['error'] = true;                
                $response['message'] = 'Could not delete item: ' .$id. 'due to database error.  Please try again';
                echoRespnse(201, $response);
            }
            
        });
        

        
$app->run();




    
?>